<?php
/**
 * Mechanism
 * 
 * LICENSE
 * 
 * This file is private intellectual property of the author. 
 * All rights reserved. Copying and illegal using is punishable by law.
 * 
 * @copyright Copyright (c) 2011 BreatheInMyVoid ( BreatheInMyVoid@gmail.com )
 */

namespace Mechanism {
	use Mechanism\Gear\IGear;
	class Mechanic {
		protected $mechanized = null;
		protected $gears = array( );
		
		public function __construct( $obj ) {
			if ( !is_object( $obj ) ) {
				// Exception
			} else {
				$this->mechanized = $obj;
			}
		}
		
		public function __call( $name, $args ) {
			if ( method_exists( $this->mechanized, $name ) ) {
				$gears_len = count( $this->gears );
				
				/* Run pre method gears */
				$method = 'pre_' . $name;
				for ( $i = 0; $i < $gears_len; ++$i ) {
					if ( method_exists( $this->gears[$i], $method ) ) {
						$this->gears[$i]->$method( $this->mechanized );
					}
				}
				
				/* Call needed metod */
				call_user_func_array( array( $this->mechanized, $name ), $args );
				
				/* Run post method gears */
				$method = 'post_' . $name;
				for ( $i = 0; $i < $gears_len; ++$i ) {
					if ( method_exists( $this->gears[$i], $method ) ) {
						$this->gears[$i]->$method( $this->mechanized );
					}
				}			
			}
		}
		
		public function add_gear( IGear $gear ) {
			array_push( $this->gears, $gear );
		}
	}
}